package com.fun.feifun.modules.business.controller;
import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fun.feifun.base.utils.http.HttpUtil;
import com.fun.feifun.modules.business.constant.InterfaceConstant;
import com.fun.feifun.modules.business.model.*;
import com.fun.feifun.modules.business.model.dto.BusinessSupplierAllDto;
import com.fun.feifun.modules.business.model.dto.BusinessSupplierGoodsDto;
import com.fun.feifun.modules.business.model.dto.BusinessUserGoodsDto;
import com.fun.feifun.modules.business.model.param.*;
import com.fun.feifun.modules.business.service.IBusinessInterfaceService;
import com.fun.feifun.modules.business.service.IBusinessSupplierGoodsService;
import com.fun.feifun.modules.business.service.IBusinessUserGoodsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fun.feifun.modules.business.service.IBusinessSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fun.feifun.base.result.Result;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;

import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 业务供应商 前端控制器
 * </p>
 *
 * @author wkf
 * @since 2024-06-04
 */
@RestController
@Api(value = "/business/business-supplier", tags = "业务供应商")
@Slf4j
@SaCheckLogin()
@RequestMapping("/business/business-supplier")
public class BusinessSupplierController {


    @Autowired
    private IBusinessSupplierService service;

    @Autowired
    private IBusinessSupplierGoodsService supplierGoodsService;

    @Autowired
    private IBusinessInterfaceService interfaceService;

    /**
     * 获取分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "获取分页信息")
    public Result<Page<BusinessSupplier>> page(@RequestBody BusinessSupplierPage param){
        Page page = new Page(param.getPage(),param.getSize());
        QueryWrapper<BusinessSupplier> wrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getCode())){
            wrapper.lambda().like(BusinessSupplier::getCode,param.getCode());
        }
        if(StringUtils.isNotEmpty(param.getContactName())){
            wrapper.lambda().like(BusinessSupplier::getType,param.getContactName());
        }
        if(StringUtils.isNotEmpty(param.getContactPhone())){
            wrapper.lambda().like(BusinessSupplier::getContactPhone,param.getContactPhone());
        }
        wrapper.lambda().eq(BusinessSupplier::getDelFlag,false);
        service.page(page,wrapper);
        return Result.success(page);
    }


    /**
     * 添加数据
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "添加或者保存")
    public Result save(@RequestBody BusinessSupplier item){
        if(service.saveOrUpdate(item)){
         return Result.success("数据添加成功！");
        }
        return Result.err("数据添加成功！");
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/del")
    @ApiOperation(value = "删除")
    public Result deleteItems(@RequestBody List<Long> ids){
        if(service.removeByIds(ids)){
            return Result.success("数据删除成功！");
        }
        return Result.err("数据删除失败");
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/findById")
    @ApiOperation(value = "查找")
    public Result findById(@RequestParam("id") Long id){
        BusinessSupplier item = service.getById(id);
        if(item==null){
            return Result.err("尚未查询到此ID");
        }
        return Result.success(item);
    }


    @PostMapping("/getSupplierGoodsList")
    @ApiOperation(value = "获取代理商商品列表")
    public Result<List<BusinessSupplierGoodsDto>> getSupplierGoodsPage(@RequestBody BusinessSupplierParam param){
        List<BusinessSupplierGoodsDto> list = supplierGoodsService.getSupplierDtoPage(param);
        return Result.success(list);
    }

    @PostMapping("/setUserGoods")
    @ApiOperation(value = "设置用户商品")
    public Result setUserGoods(@RequestBody BusinessSupplierGoodsParam param){
        List<BusinessSupplierGoodsParam.GoodsFees> goodsList = param.getGoodsList();
        Set<Long> set = goodsList.stream().map(it -> it.getGoodsId()).collect(Collectors.toSet());
        if(set.size()!=param.getGoodsList().size()){
            return Result.success("用户设置中的商品重复,请检查。");
        }
        if(supplierGoodsService.saveSupplierGoods(param)){
            return Result.success("设置成功");
        }else{
            return Result.success("设置失败");
        }
    }

    @GetMapping("/all")
    @ApiOperation(value = "所有供货商")
    public Result< List<BusinessSupplierAllDto>> getAll(){
        QueryWrapper<BusinessSupplier> wrapper=new QueryWrapper();
        wrapper.lambda().eq(BusinessSupplier::getDelFlag,false);
        List<BusinessSupplier> all = service.list(wrapper);
        List<BusinessSupplierAllDto> list = all.stream().map(it -> it.toDto()).collect(Collectors.toList());
        return Result.success(list);
    }



    @GetMapping(value = "/getBalance")
    @ApiOperation(value = "查询供货商的余额")
    public Result getBalance(@RequestParam("id") Long id) throws Exception {
        BusinessSupplier supplier = service.getById(id);
        Integer interfaceType = supplier.getInterfaceType();
        if(interfaceType==null){
            return Result.err("未配置供货商接口");
        }
        QueryWrapper<BusinessInterface> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessInterface::getInterfaceType,interfaceType)
                .eq(BusinessInterface::getCategory, InterfaceConstant.getbBalance);
        BusinessInterface businessInterface = interfaceService.getOne(wrapper);
        if(businessInterface==null){
            return Result.err("未找到对应接口");
        }
        Map<String,String> param=new HashMap<>();
        param.put("userid",supplier.getInterfaceUserId());
        param.put("key",supplier.getInterfaceSecretKey());
        Map<String, String> getbalance = interfaceService.getbalance(businessInterface, param);
        return Result.success("查询成功",getbalance.get("balance"));
    }


    @GetMapping("/generateSecretKey")
    @ApiOperation(value = "生成密匙")
    public Result<BusinessSupplier> generateSecretKey(@RequestParam("supplierId") Long supplierId){

        BusinessSupplier supplier=service.getById(supplierId);
        // 创建一个SecureRandom实例
        SecureRandom random = new SecureRandom();
        // 密钥长度为16字节（128位）
        byte[] keyBytes = new byte[16];
        // 生成随机密钥
        random.nextBytes(keyBytes);
        // 将字节转换为Base64编码字符串
        String key = Base64.getEncoder().encodeToString(keyBytes);
        supplier.setSecretKey(key);
        boolean update = service.updateById(supplier);
        if(update){
            return Result.success("生成成功");
        }else{
            return Result.success("生成失败");
        }
    }
}

